#!/usr/bin/env python
# -*- coding: utf-8 -*-

from __future__ import division

import os.path
import re
import tornado.httpserver
import tornado.ioloop
import tornado.options
import tornado.web
import base64
import hashlib
import math
import random
import ConfigParser
from tornado.options import define, options

import frontend
import backend

class Application(tornado.web.Application):
    def __init__(self):

        cf = ConfigParser.ConfigParser()
        cf.read("config.conf")
        
        define("port", default=cf.getint("db","port"), help="run on the given port", type=int)
        define("page_limit", default=cf.getint("setting","limit"), help="page limit")

        handlers = [
            (r"/a/post/(.*)",backend.PostHandler),
            (r"/a/postfile.*",backend.PostfileHandler),
            (r"/a/upload/(.*)",backend.UploadHandler),
            (r"/a/posts/(.*)/?",backend.PostsHandler),
            (r"/a/dashboard/(.*)",backend.DashboardHandler),
            (r"/a/files/(.*)/?",backend.FilesHandler),
            (r"/a/setting/(.*?)/?",backend.SettingHandler),
            (r"/login|/logout",backend.AuthHandler),
            (r"/t/(.*)\.html",frontend.ShowHandler),
            (r"/p/(\d+?)|/?",frontend.MainHandler),
            (r"/c/(.+)",frontend.CateHandler),
        ]
        
        settings = dict(
            site_title=u"byron's blog",
            template_path=os.path.join(os.path.dirname(__file__),"templates"),
            static_path=os.path.join(os.path.dirname(__file__), "static"),
            cookie_secret="61oETzKXQAGaYdkL5gEmGeJJFuYh7EQnp2XdTP1o/Vo=",
            xsrf_cookies=True,
            ui_modules={"Page": PageModule},
            debug=True,
        )
        
        tornado.web.Application.__init__(self,handlers,**settings)

# UI Module
class PageModule(tornado.web.UIModule):
    def render(self,entry,limit=None):
        limit = limit or options.page_limit
        pages = int(math.ceil(int(entry["rowset"].count())/limit))
        return self.render_string("modules/page.html",url=entry['url'],pages=pages,page=entry['page'])

def main():
    tornado.options.parse_command_line()
    http_server = tornado.httpserver.HTTPServer(Application())
    http_server.listen(options.port)
    tornado.ioloop.IOLoop.instance().start()

if __name__ == "__main__":
    main()
